package com.java.array;

public class ArrayFindDemo {
    public static void main(String[] args) {
        //定义数组
       /* int[] arr = {10,15,21,3,8,5};
        int num = 1;

        //调用查找方法
        int position = find(arr,num);
        System.out.println("查找结果为："+position);

        //查找最大值
        int Max = max(arr);
        System.out.println("数组最大值为："+Max);

        //冒泡排序
        bubbleSort(arr);
        for(int n : arr){
            System.out.println(n);
        }*/

        //二分查找
        int[] array3 = {1,2,3,4,5,6,7,8,9,10};
        System.out.println("查找结果为："+binarySearch(array3,9));
    }

    public static int find(int[] array,int num) {
        //遍历数组，将每个元素和查找进行比较
        for(int i = 0; i < array.length; i++) {
            if(array[i] == num) {
                return i;
            }
        }
        //数组中没有找到
        return -1;
    }

    public static int max(int[] array){
        int max = array[0];
        for (int i = 1; i < array.length; i++){
            if (array[i] > max){
                max = array[i];
            }
        }
        //返回最大值
        return max;
    }

    public static void bubbleSort(int[] array){
        //外层循环控制比较轮数 n-1
        for(int i = 0; i < array.length-1; i++){
            //内层循环控制每轮比较次数 n-i-1
            for(int j = 0; j < array.length-i-1; j++){
                //比较相邻的两个元素，如果前一个元素大于后一个元素，则交换位置
                if(array[j] > array[j+1]){
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
    }

    public static int binarySearch(int[] array, int num){

        int left = 0;
        int right = array.length-1;

        while(left <= right){
            int mid = (left+right)/2;
            if(array[mid] == num){
                return mid;
            }else if(array[mid] > num){
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }

        return binarySearch(array, num);
    }
}
